package com.beulemai.reader;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import comic.Comic;

/**
 * Main Activity Dynamically loads all available comics and their preferences
 * and displays them in a list. After selecting one it calls ComicViewActivity.
 * Will save the preferences if closed.
 */
public class WebComicReaderActivity extends ListActivity {
	HashMap<String, Comic> map;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		SharedPreferences progress = getSharedPreferences("Progress",
				MODE_PRIVATE);

		// Load the Comic classes dynamically
		ArrayList<Comic> list = loadComics();

		// create a map from the display name to the comic, since a list
		// can only hold strings. That way we know which comic is behind it
		map = new HashMap<String, Comic>();
		for (Comic comic : list) {
			// read the comic reading progress from a settings file
			comic.lastread = progress.getInt(comic.display_name, -1);
			map.put(comic.get_display_name(), comic);
		}

		// create a list of all comic display names for the list activity
		String[] values = new String[map.size()];
		int i = 0;
		for (String string : map.keySet()) {
			values[i] = string;
			i++;
		}

		// connect the adapter with the list activity
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, values);
		setListAdapter(adapter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// get the display name based on the position in the list
		String item = (String) getListAdapter().getItem(position);
		Comic comic = map.get(item);
		Toast.makeText(this, R.string.open_message, Toast.LENGTH_SHORT).show();
		// Start the ComicViewActivity
		Intent intent = new Intent(this, ComicViewActivity.class);
		intent.putExtra("comic", comic);
		startActivityForResult(intent, 42);
	}

	@Override
	protected void onStop() {
		super.onStop();

		SharedPreferences settings = getSharedPreferences("Progress", 0);
		SharedPreferences.Editor editor = settings.edit();
		for (String s : map.keySet()) {
			Comic comic = map.get(s);
			editor.putInt(comic.display_name, comic.lastread);
		}
		// Commit the edits!
		editor.commit();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// Take back the modified comic object
		if (requestCode == 42) {
			Bundle extras = data.getExtras();
			Comic c = (Comic) extras.getSerializable("comic");
			map.put(c.get_display_name(), c);
		}
	}

	/**
	 * Loads and instantiates all comic objects which are listed in the comic
	 * array in arrays.xml
	 * 
	 * @return the list of comic objects
	 */
	protected ArrayList<Comic> loadComics() {
		ArrayList<Comic> list = new ArrayList<Comic>();
		String[] names = getResources().getStringArray(R.array.comics);

		for (String name : names) {
			try {
				Class<?> c = Class.forName("comic." + name);
				Object o = c.newInstance();
				if (o instanceof Comic) {
					list.add((Comic) o);
				}
			} catch (ClassNotFoundException e) {
				//Class listed in the list does not exist
				//Can be ignored
			} catch (IllegalAccessException e) {
				//Default Constructor cannot be called
				//The class is no subclass of Comic, so it can be ignored
			} catch (InstantiationException e) {
				//Some other error appeared in the constructor
			}
		}

		return list;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, 0, Menu.NONE, R.string.about);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == 0) {
			aboutbox();
		}
		return true;
	}

	/**
	 * Shows a messagebox with a text
	 */
	protected void aboutbox() {
		AlertDialog ad = new AlertDialog.Builder(this).create();
		ad.setCancelable(false); // This blocks the 'BACK' button
		ad.setMessage(getResources().getString(R.string.about_message));
		ad.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		ad.show();
	}

}